import { Dep } from "./Dep.js";
import { Watcher } from "./Watcher.js";
export function observer(vm, data) {
    const dep = new Dep();
    Object.keys(data).forEach((key) => {
        let internalValue = data[key];
        Object.defineProperty(vm, key, {
            get() {
                if (Dep.target) {
                    dep.pushDep(Dep.target);
                }
                return internalValue;
            },
            set(newValue) {
                if (newValue === internalValue) {
                    return;
                }
                internalValue = newValue;
                dep.notify();
            }
        });
    });
    new Proxy(vm, {
        get(target, p, receiver) {
            console.log(...arguments, 'get');
        },
        set(target, p, newValue, receiver) {
            console.log(...arguments, 'set');
            return true;
        },
    });
}
export function complie(vm) {
    const el = document.querySelector(vm.$el);
    if (!el) {
        throw new Error('没有找到要绑定的元素');
    }
    const reg = /\{\{(.*)\}\}/;
    const fg = document.createDocumentFragment();
    while (el.firstChild) {
        const child = el.firstChild;
        if (child.nodeType === Node.ELEMENT_NODE) {
            if (reg.test(child.innerText || '')) {
                const vmKey = RegExp.$1.trim();
                new Watcher(vm, child, vmKey);
            }
            else {
                Array.from(child.attributes).forEach((attr) => {
                    const attrName = attr.name;
                    if (attrName === 'v-model') {
                        const vmKey = RegExp.$1.trim();
                        child.addEventListener('input', (ev) => {
                            const target = ev.target;
                            vm[vmKey] = target.value;
                        });
                    }
                });
            }
        }
        else if (child.nodeType === Node.TEXT_NODE && reg.test(child.nodeValue || '')) {
            const vmKey = RegExp.$1.trim();
            new Watcher(vm, child, vmKey);
        }
        fg.appendChild(child);
    }
    el.appendChild(fg);
}
